package com.hr.checkrepetition.component;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import org.springframework.stereotype.Component;

import java.util.concurrent.*;

@Component
public class CompletableThreadPoolExecutor {



    private final ExecutorService executorService;


    public void submitTask(Task task) {
        CompletableFuture.supplyAsync(() -> {
            task.exec();
            return null;
        }, executorService);

    }


    private CompletableThreadPoolExecutor() {
        int processors = Runtime.getRuntime().availableProcessors();
        executorService = new ThreadPoolExecutor(processors * 2,
                processors * 2,
                0L,
                TimeUnit.SECONDS,
                new LinkedBlockingQueue<>(10000),
                getThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }

    private ThreadFactory getThreadFactory() {
        return new ThreadFactoryBuilder().setNameFormat("executor-exec-%d").build();
    }

    public ExecutorService getOriginalExecutor() {
        return executorService;
    }

    @FunctionalInterface
    public interface Task {

        void exec();

    }

}
